package com.comp490.pattern;

import java.util.List;

import com.comp490.bullet.Bullet;
import com.comp490.shooter.GameView;
import com.comp490.sprite.Ship;

public class CircularPattern extends BulletPattern
{
    private final int N;
    private final int STEP;
    private int delta;
    private final float[][] THETA;

    public CircularPattern(int step, List<Bullet> b, GameView gv, boolean act)
    {
        super(b, gv, act);
        STEP = step;
        delta = step;
        bullets = b;
        N = bullets.size();
        THETA = new float[2][N];

        float angle;
        for(int i = 0; i < N; i++)
        {
            angle = 2 * i * PI / N;
            THETA[0][i] = android.util.FloatMath.cos(angle);
            THETA[1][i] = android.util.FloatMath.sin(angle);
        }
    }

    public void moveAndCheckCollision(List<? extends Ship> ships)
    {
        if(!active)
            return;
        active = false;
        for(int i = 0; i < N; i++)
        {
            Bullet bullet = bullets.get(i);
            if(!bullet.isActive())
                continue;
            
            bullet.setX(delta * THETA[0][i] + x);
            bullet.setY(delta * THETA[1][i] + y);
            if(!bullet.boundsCheck(gameView))
            {
                bullet.setActive(false);
                continue;
            }
            
            for(int j = 0; j< ships.size(); j++)
            {
            	if(ships.get(j).isActive() && bullet.collisionCheck(ships.get(j)))
                {
            		ships.get(j).hit(bullet.getDamage());
                    bullet.setActive(false);
                    break;
                }
            }
            active |= bullet.isActive();
        }
        delta += STEP;
    }

    @Override
    public void reset()
    {
    	for(int i = 0; i < bullets.size(); i++)
    	{
            bullets.get(i).setActive(true);
            bullets.get(i).setX(x);
            bullets.get(i).setY(y);
    	}
        delta = STEP;
        active = true;
    }

    public String toString()
    {
        return bullets.toString();
    }
}